﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Common;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using TRPOP.CRM.Component.Model;
using TRPOP.Common;

namespace TRPOP.CRM.Component.DALSQLServer
{
    public class RolePermissionDAL
    {

        private static TRPOP.ComSqlDAL.ICommonDAL CommonDAL = new TRPOP.ComSqlDAL.CommonDAL();
        #region 私有的方法
        ///	<summary>
        ///	从Table取数据到实体
        ///	</summary>
        ///	<param name="oDataRow">数据行</param>
        ///	<returns>返回实体</returns>
        private static RolePermissionInfo ParseRowTomodel(DataRow oDataRow)
        {
            RolePermissionInfo oInfo = new RolePermissionInfo();
            oInfo.iPermissionID = oDataRow["iPermissionID"] is DBNull ? 0 : (int)oDataRow["iPermissionID"];
            oInfo.iSystemRoleID = oDataRow["iSystemRoleID"] is DBNull ? 0 : (int)oDataRow["iSystemRoleID"];
            oInfo.nvcRemark = oDataRow["nvcRemark"] is DBNull ? "" : (string)oDataRow["nvcRemark"];
            return oInfo;
        }


        ///	<summary>
        ///	通用的添加存储过程的变量
        ///	</summary>
        ///	<param name="osdDataBase">SqlDatabase</param>
        ///	<param name="odbCommand">DbCommand</param>
        ///	<param name="oInfo">实体</param>
        private static RolePermissionInfo ParseModeltoParam(SqlDatabase odbDataBase, DbCommand odbCommand, RolePermissionInfo oInfo)
        {
            odbDataBase.AddInParameter(odbCommand, "@iPermissionID", System.Data.DbType.Int32, oInfo.iPermissionID);
            odbDataBase.AddInParameter(odbCommand, "@iSystemRoleID", System.Data.DbType.Int32, oInfo.iSystemRoleID);
            odbDataBase.AddInParameter(odbCommand, "@nvcRemark", System.Data.DbType.String, oInfo.nvcRemark);
            return oInfo;
        }


        #endregion

        ///	<summary>
        ///	 更新或添加
        ///	</summary>
        ///	<param name="oInfo"></param>
        ///	<returns>bool</returns>
        public bool Save(RolePermissionInfo oInfo)
        {
            bool flag = false;
            try
            {
                SqlDatabase odbDataBase = new SqlDatabase(SystemInfoHelper.getSystemInfo().DataBaseConnection);
                DbCommand odbCommand = odbDataBase.GetStoredProcCommand("RolePermission_Save");
                ParseModeltoParam(odbDataBase, odbCommand, oInfo);
                odbDataBase.ExecuteNonQuery(odbCommand);
                flag = true;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
            return flag;
        }

        ///	<summary>
        ///	根据Primary Key获取信息实体
        ///	</summary>
        ///	<param name="intiPermissionID"></param>
        ///	<param name="intiSystemRoleID"></param>
        ///	<returns>RolePermissionInfo</returns>
        public RolePermissionInfo GetInfoById(int intiPermissionID, int intiSystemRoleID)
        {
            RolePermissionInfo oInfo = null;
            string strSqlString = "SELECT * FROM RolePermission WHERE  iPermissionID=" + intiPermissionID + "   AND  iSystemRoleID=" + intiSystemRoleID + "    ";
            try
            {
                DataSet oDataSet = CommonDAL.GetDataSet(strSqlString, SystemInfoHelper.getSystemInfo().DataBaseConnection);
                DataTable oDataTable = oDataSet.Tables[0];
                if (oDataTable.Rows.Count == 1)
                {
                    oInfo = ParseRowTomodel(oDataTable.Rows[0]);
                }
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
            return oInfo;
        }

        ///	<summary>
        ///	 根据Primary Key删除信息实体
        ///	</summary>
        ///	<param name="intiPermissionID"></param>
        ///	<param name="intiSystemRoleID"></param>
        ///	<returns>bool</returns>
        public bool DeleteInfoById(int intiPermissionID, int intiSystemRoleID)
        {
            string strSqlString = "DELETE FROM RolePermission WHERE   iPermissionID=" + intiPermissionID + "   AND  iSystemRoleID=" + intiSystemRoleID + "    ";
            try
            {
                return CommonDAL.ExeSQLQuery(strSqlString, SystemInfoHelper.getSystemInfo().DataBaseConnection) == EnumSubmitResult.Success;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }

        ///	<summary>
        ///	 获取信息列表（无分页）
        ///	</summary>
        ///	<param name="intTopn">前N条，为0时表示所有符合条件的</param>
        ///	<param name="strCondition">自定义条件，要以And开头</param>
        ///	<param name="strOrderby">排序，不需要Order by </param>
        ///	<returns>List<RolePermissionInfo></returns>
        public List<RolePermissionInfo> GetListByCondition(int intTopn, string strCondition, string strOrderby)
        {
            List<RolePermissionInfo> oList = new List<RolePermissionInfo>();
            string strSql = CommonDAL.strbuildSqlForList(intTopn, strCondition, strOrderby, "RolePermission");
            try
            {
                DataSet oDataSet = CommonDAL.GetDataSet(strSql, SystemInfoHelper.getSystemInfo().DataBaseConnection);
                DataTable oDataTable = oDataSet.Tables[0];
                foreach (DataRow otempRow in oDataTable.Rows)
                {
                    oList.Add(ParseRowTomodel(otempRow));
                }
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
            return oList;
        }


        public bool DeleteByRoleId(int intiSystemRoleID)
        {
            string strSqlString = "DELETE  FROM RolePermission WHERE  iSystemRoleID=" + intiSystemRoleID + "    ";

            try
            {
                return CommonDAL.ExeSQLQuery(strSqlString, SystemInfoHelper.getSystemInfo().DataBaseConnection) == EnumSubmitResult.Success;
            }
            catch (Exception oeException)
            {
                throw new Exception(oeException.Message, oeException);
            }
        }


        public bool SaveRolePermission(List<int> intiPermissionIDs, int intiSystemRoleID)
        {

            bool blnReturn = false;

            //根据用户ID删除用的所有权限
            DeleteByRoleId(intiSystemRoleID);

            //增加新的关系
            SqlDatabase osdDataBase = new SqlDatabase(SystemInfoHelper.getSystemInfo().DataBaseConnection);
            DbConnection odbConnection = osdDataBase.CreateConnection();
            odbConnection.Open();
            DbTransaction odbTransaction = odbConnection.BeginTransaction();
            try
            {
                //插入 用户id权限id 关系
                string strStoreProcedure = "RolePermission_Save";
                DbCommand odbCommand = osdDataBase.GetStoredProcCommand(strStoreProcedure);

                foreach (int intTempID in intiPermissionIDs)
                {
                    //清除原有参数信息
                    odbCommand.Parameters.Clear();

                    osdDataBase.AddInParameter(odbCommand, "@iPermissionID", System.Data.DbType.Int32, intTempID);
                    osdDataBase.AddInParameter(odbCommand, "@iSystemRoleID", System.Data.DbType.Int32, intiSystemRoleID);
                    osdDataBase.AddInParameter(odbCommand, "@nvcRemark", System.Data.DbType.String, string.Empty);

                    osdDataBase.ExecuteNonQuery(odbCommand, odbTransaction);
                }

                odbTransaction.Commit();

                blnReturn = true;
            }
            catch (Exception)
            {
                odbTransaction.Rollback();
            }
            finally
            {
                odbConnection.Close();
            }
            return blnReturn;
        }

    }
}
